<template>
  <div class="user">
    <section class="query-form">
      <el-form :inline="true" :model="user" ref="queryForm">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户" />
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-select v-model="user.state">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </section>
    <section class="base-table">
      <section class="action">
        <el-button type="primary" @click="handleCreate" v-has="'user-create'"
          >新增</el-button
        >
        <el-button
          type="danger"
          @click="handlePatchDel"
          v-has="'user-patch-delete'"
          >批量删除</el-button
        >
      </section>
      <el-table :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :formatter="column.formatter"
          v-for="column in columns"
          :key="column.prop"
        ></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="mini"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange"
      />
    </section>
    <el-dialog title="用户新增" v-model="showModal">
      <el-form
        :model="userForm"
        label-width="100px"
        :rules="userFormRules"
        ref="userFormRef"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            :disabled="action === 'edit'"
            v-model="userForm.userName"
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            :disabled="action === 'edit'"
            v-model="userForm.userEmail"
            placeholder="请输入用户邮箱"
          >
            <template #append> @imooc.com </template>
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="userForm.job" placeholder="请输入岗位" />
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state">
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="系统角色" prop="roleList">
          <el-select
            style="width: 100%"
            v-model="userForm.roleList"
            placeholder="请选择用户系统角色"
            multiple
          >
            <el-option
              v-for="list in roleList"
              :key="list._id"
              :label="list.roleName"
              :value="list._id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="deptId">
          <el-cascader
            style="width: 100%"
            v-model="userForm.deptId"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRaw
} from 'vue'
import utils from '@/utils/utils'
export default {
  name: 'User',
  setup() {
    const globalProperties =
      getCurrentInstance().appContext.config.globalProperties

    const $api = globalProperties.$api
    const queryForm = ref(null)
    const userFormRef = ref(null)

    const roleList = ref([])
    const deptList = ref([])
    const action = ref('add')

    const user = reactive({
      state: 1
    })
    const userForm = reactive({
      state: 3
    })

    const userFormRules = reactive({
      userName: [
        {
          required: true,
          message: '请输入用户名称',
          trigger: 'blur'
        }
      ],
      userEmail: [
        {
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }
      ],
      deptId: [
        {
          required: true,
          message: '请选择部门',
          trigger: 'blur'
        }
      ]
    })

    const userList = ref([])
    const pager = reactive({
      pageNum: 1,
      pageSize: 10
    })
    const checkedUserIds = ref([])

    const columns = reactive([
      {
        label: '用户ID',
        prop: 'userId'
      },
      {
        label: '用户名',
        prop: 'userName'
      },
      {
        label: '用户邮箱',
        prop: 'userEmail'
      },
      {
        label: '用户角色',
        prop: 'role',
        formatter(row, column, value) {
          return {
            0: '管理员',
            1: '普通用户'
          }[value]
        }
      },
      {
        label: '用户状态',
        prop: 'state',
        formatter(row, column, value) {
          return {
            0: '所有',
            1: '在职',
            2: '离职',
            3: '试用期'
          }[value]
        }
      },
      {
        label: '注册时间',
        prop: 'createTime',
        formatter(row, column, value) {
          return utils.formatDate(new Date(value))
        }
      },
      {
        label: '最后登录时间',
        prop: 'lastLoginTime',
        formatter(row, column, value) {
          return utils.formatDate(new Date(value))
        }
      }
    ])

    const showModal = ref(false)

    onMounted(() => {
      getUserList()
      getDeptList()
      getRoleList()
    })

    const getUserList = async () => {
      const params = { ...user, ...pager }
      const { list, page } = await $api.getUserList(params)
      userList.value = list
      pager.total = page.total
    }

    const handleQuery = () => {
      getUserList()
    }
    const handleReset = () => {
      queryForm.value.resetFields()
    }
    const handleResetDialogForm = () => {
      userFormRef.value.resetFields()
      console.log('userForm >>> ', userForm)
    }

    const handleEdit = (row) => {
      showModal.value = true
      action.value = 'edit'
      nextTick(() => {
        Object.assign(userForm, row)
      })
    }

    const handleDelete = async (row) => {
      await $api.userDel({
        userIds: [row.userId]
      })
      globalProperties.$message.success('删除成功')
      getUserList()
    }
    const handlePatchDel = async () => {
      if (!checkedUserIds.value.length) {
        globalProperties.$message.error('请选择要删除的用户')
        return
      }
      const res = await $api.userDel({
        userIds: checkedUserIds.value
      })
      if (res.modifiedCount > 0) {
        globalProperties.$message.success('删除成功')
        getUserList()
      } else {
        globalProperties.$message.error('删除失败')
      }
    }

    const handleCurrentChange = (current) => {
      pager.pageNum = current
      getUserList()
    }

    const handleSelectionChange = (val) => {
      const tempIds = []
      val.forEach((v) => tempIds.push(v.userId))
      checkedUserIds.value = tempIds
    }

    const handleCreate = () => {
      action.value = 'add'
      showModal.value = true
    }

    const getDeptList = async () => {
      const res = await $api.getDeptList()
      deptList.value = res
    }
    const getRoleList = async () => {
      const { list } = await $api.getRoleList()
      roleList.value = list
    }

    const handleSubmit = () => {
      userFormRef.value.validate(async (valid) => {
        if (valid) {
          const params = toRaw(userForm)
          params.userEmail += '@imooc.com'
          params.action = action.value

          const res = await $api.userSubmit(params)
          // if (res) {
          globalProperties.$message.success('操作成功')
          showModal.value = false
          handleResetDialogForm()
          getUserList()
          // }
        }
      })
    }
    const handleClose = () => {
      showModal.value = false
      handleResetDialogForm()
    }

    return {
      user,
      userForm,
      pager,
      userList,
      userFormRules,
      columns,
      action,
      checkedUserIds,
      handleEdit,
      getUserList,
      handleQuery,
      handleReset,
      queryForm,
      userFormRef,
      handleCurrentChange,
      handleDelete,
      handlePatchDel,
      handleSelectionChange,
      handleCreate,
      showModal,
      getRoleList,
      getDeptList,
      roleList,
      deptList,
      handleSubmit,
      handleClose,
      handleResetDialogForm
    }
  }
}
</script>

<style lang="scss" scoped></style>
